<?php
/**
 * Created by PhpStorm.
 * User: surface
 * Date: 2018/12/16
 * Time: 20:35
 */
namespace app\common\model;
use app\common\model\Room as RoomModel;
use app\common\model\RoomBooking as BookingModel;
use app\common\model\Balance as BalanceModel;
use app\common\model\Payments as PaymentsModel;
use think\Validate;
use think\helper\Time;

class RoomBooking extends Common
{
    protected $rule = [
        'name'          => 'require|max:6',
        'mobile'          => 'require|max:11',
        'bn'          => 'require',
        'type'          => 'require',
        'booking_time'          => 'require',
        'bn'          => 'require',
        'memo'          => 'require',
    ];
    protected $msg = [
        'name.require'  => '请输入联系人',
        'name.max'      => '联系人名称长度最大6位',
        'mobile.require'  => '请输入联系人电话',
        'mobile.max'  => '联系人电话长度最大11位',
        'type.require'          => '请选择预约类型',
        'booking_time.require'          => '请选择预约时间',
         'bn.require'          => '请选择房间',
        'memo.require'          => '请输入备注'
    ];

    /**
     * 房间支付完成后
     * @param $booking_id  预约单id
     * @param $type 1.钱包支付  0.其他支付
     * @param $billNo 支付单号
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function  payAfter($user_id, $booking_id, $type, $billNo){
        $where['id'] = $booking_id;
        $booking = $this->field("*")->where($where)->select();
        $booking['pay_status'] = 1;
        if($type == 1){
            $balanceModel = new BalanceModel();
            $balanceModel->change($user_id, 1, $booking['price'], $billNo);
        }
        $this->save($booking,$where);
    }

    public function tableData($post,$isPage=true)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }
        $tableWhere = $this->tableWhere($post);
        //print_r($tableWhere);exit;
        $query = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order']);
        if($isPage){
            $list = $query->paginate($limit);
            $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = $list->total();
        }else{
            $list = $query->select();
            $data = $this->tableFormat($list);         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型
            $re['count'] = count($list);
        }
        foreach ($data as &$v)
        {
            $v['booking_time'] = date('Y-m-d', $v['booking_time']);
        }
        $re['code'] = 0;
        $re['msg'] = '';
        $re['data'] = $data;
        return $re;
    }

    public function  to_shop($id){
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];
        //扣减库存操作
        $bookingModel = new BookingModel();
        /*$booking = $bookingModel->field('*')->where(['id'=>$id])->find();
        if($booking['taocan'] && $booking['taocan'] != ""){
            $stockListModel = new StockListModel();
            $taocan = json_decode($booking['taocan'], true);
            foreach ($taocan['goods'] as &$v){
                $stockListModel->change($booking['user_id'],$v['id'],$v['total'],1,"",$booking['bn']);
            }
        }*/
        $data['to_shop'] = 1;
        $this->save($data,['id'=>$id]);
        return $result;
    }
    public function saveData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];
        $roomModel = new RoomModel();
        $room = $roomModel->getOne($data['room_id']);
        $data['bn'] = $room['data']['bn'];
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            $bookingModel = new BookingModel();
            $old = $bookingModel->where('id',$data['id'])->find();
            if($old['type'] == 1){
                $data['type'] = 1;
            }
            $data['ctime'] = $old['ctime'];
            $data['booking_time'] = strtotime($data['booking_time']);
            //$data['price'] = $old['price'];  看不懂的操作
            $data['user_id'] = $old['user_id'];
            if (!$this->allowField(true)->save($data,['id'=>$data['id']]))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
        }
        return $result;
    }

    /**
     * 默认排序
     * @param $post
     * @return mixed
     * User: wjima
     * Email:1457529125@qq.com
     * Date: 2018-01-11 16:32
     */
    protected function tableWhere($post)
    {
        $whereOr = [];
        $where = '1=1 ';
        if (isset($post['name']) && $post['name'] != "") {
            $where .= 'and name like \'%'.$post['name'].'%\'';//[] = ['name', 'like',  $post['name']];
        }
        if (isset($post['id']) && $post['id'] != "") {
            $where[] = ['id', 'in', $post['id']];
        }

        if(isset($post['mobile'])&& $post['mobile'] != ""){
            //$where[] = ['bn', 'like', '%'.$post['mobile'].'%'];
            $where .= 'and mobile like \'%'.$post['mobile'].'%\'';
        }
        
        if(isset($post['booking_time'])&& $post['booking_time'] != ""){
            //$where[] = ['bn', 'like', '%'.$post['mobile'].'%'];
            $where .= 'and FROM_UNIXTIME(booking_time,\'%Y-%m-%d\')="'.$post['booking_time'].'"';
        }
        
        if( $post['type'] == "today") {
            $hour=date("G");
            if($hour < 3){
                $begintime=strtotime(date("Y-m-d",strtotime("-1 day"))." 0:0:0");
                $endtime=strtotime(date("Y-m-d",strtotime("-1 day"))." 23:59:59");
            }else{
                $begintime=strtotime(date("Y-m-d",time())." 0:0:0");
                $endtime=strtotime(date("Y-m-d",time())." 23:59:59");
            }
            $where .= 'and booking_time BETWEEN '.$begintime.' AND '.$endtime;

            /*list($start, $end) = Time::today();
            list($yest_start, $yest_end) = Time::yesterday();
            if($yest_end >  time()-3600*3) {
                $where .= 'and booking_time BETWEEN '.$yest_start.' AND '.($yest_end+3600*3);
            } else {
                $where .= 'and booking_time BETWEEN '.$start.' AND '.($end+3600*3);
            }*/
        }
        $where .= ' and pay_status=1';
        //$where['pay_status'] = 1;
        $result['where'] = $where;

        $result['whereOr'] = $whereOr;

        $result['field'] = "*";
        $result['order'] = ['booking_time' => 'desc'];
        return $result;
    }

    /**
     * 接口预约
     * @param $data
     * @return array
     */
    public function createBooking($data){
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> []
        ];
        $roomModel = new RoomModel();
        $room = $roomModel->getOne($data['room_id']);
        $data['price'] = $room['data']['price'];
       /* if($data['taocan'] != ""){
            $taocan = json_decode($data['taocan']);
            $data['price'] = $taocan['price'];
        }*/
        if($data['taocan'] && $data['taocan'] != "") {
            $taocan = json_decode($data['taocan'], JSON_FORCE_OBJECT);
            $data['price'] = $taocan['price'];
        }else{
            //订房定金
            $data['price'] = 100;
        }
        $data['price'] = 100;
        $data['ctime'] = time();
        $data['bn'] = $room['data']['bn'];
        $data['booking_time'] = strtotime($data['booking_time']);

        $begintime=strtotime(date("Y-m-d",$data['booking_time'])." 0:0:0");
        $endtime=strtotime(date("Y-m-d",$data['booking_time'])." 23:59:59");
        $hour=date("G");
        if($hour >= 3) {
            if (strtotime(date("Y-m-d", $data['booking_time'])) < $begintime) {
                $result['status'] = false;
                $result['msg'] = "该时间不能被预约";
                return $result;
            }
        }
        $tableWhere['field'] = "*";
        $where[] = ['booking_time', ['EGT',$begintime],['ELT',$endtime],'and'];
        $where[] = [ 'room_id','=', $room['data']['id']];
        $where[] = ['pay_status', '=', 1];
        $booking = $this->field('*')->where($where)->select();
        if(!$booking->isEmpty()){
            $result['status'] = false;
            $result['msg'] = "温馨提示，此房今日已预定，请选择明日";
            return $result;
        }
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            $result['data'] = $this->insertGetId($data);
        }
        return $result;
    }

    /**
     * 后台用
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> []
        ];
        $roomModel = new RoomModel();
        $room = $roomModel->getOne($data['room_id']);
        $data['bn'] = $room['data']['bn'];
        $data['price'] = 0;
        $data['ctime'] = time();
        $data['booking_time'] = strtotime($data['booking_time']);
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            if (!$this->allowField(true)->save($data))
            {
                $result['status'] = false;
                $result['msg'] = '保存失败';
            }
            $result['data'] = $data;
        }
        return $result;
    }

    /**
     * 预约单支付后执行更新
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay($id, $code, $trade_no = ""){
        $return_data = array(
            'status' => false,
            'msg' => '订单支付失败',
            'data' => array()
        );
        $where = [];
        $where['id'] = $id;
        $where['pay_status'] = 0;
        $order = $this->where($where)->find();
        if(!$order)
        {
            return $return_data;
        }
        if($order['pay_status'] == 1)
        {
            $return_data['msg'] = '订单支付失败，该订单已支付';
            $return_data['data'] = $order;
            return $return_data;
        }
        else
        {
            $booking = $this->where(['id' => $id])->find();
            $begintime=strtotime(date("Y-m-d",$booking['booking_time'])." 0:0:0");
            $endtime=strtotime(date("Y-m-d",$booking['booking_time'])." 23:59:59");
            $tableWhere['field'] = "*";
            $where[] = ['booking_time', ['EGT',$begintime],['ELT',$endtime],'and'];
            $where[] = [ 'room_id','=', $booking['room_id']];
            $where[] = ['pay_status', '=', 1];
            $booking = $this->field('*')->where($where)->select();
            if(!$booking->isEmpty()){
                //执行退款并取消订单
                $data['pay_status'] = 2;
                $data['payment_code'] = $code;
                $paymentsModel = new PaymentsModel();
                $paymentInfo = $paymentsModel->getPayment($booking['payment_code'], $paymentsModel::PAYMENT_STATUS_YES);
                $conf = json_decode($paymentInfo['params'], true);

                if($booking['payment_code'] == 'balance'){
                    $balanceModel = new BalanceModel();
                    $balanceModel->change($booking['user_id'],2, $booking['price'], $booking['id']);
                }else{
                    $payment = \org\Payment::create($booking['payment_code'], $conf);       //'wechatpay' or alipa
                    $res = $payment->refund($trade_no, 50);
                }
            }else{
                $data['pay_status'] = 1;
                $data['payment_code'] = $code;
            }
        }
        $result = $this->where('id', 'eq', $id)->update($data);
        $return_data['data'] = $result;
        if($result !== false)
        {
            $return_data['status'] = true;
            $return_data['msg'] = '订单支付成功';
        }
        return $return_data;
    }

    public function getBookingList($user_id, $page=1, $limit=10)
    {

        $result = [
            'status' => true,
            'msg'    => '获取成功',
            'data'   => [ ]
        ];
       // $begintime=strtotime(date("Y-m-d",strtotime("-7 day"))." 0:0:0");
        $condition1 = [
            ['user_id', '=', $user_id],
            ['pay_status', '=', '1'],
            //['ctime', ['EGT',$begintime],['ELT',time()],'and'],

            ['isdel', '=', '0']
        ];

        $data = $this->where($condition1)->order('booking_time desc')->page($page, $limit)->select();
        foreach ($data as &$v)
        {
            $v['booking_time'] = date('Y-m-d', $v['booking_time']);
            $v['ctime'] = date('Y-m-d h:i', $v['ctime']);
        }
        $result['data'] = $data;
        $count = $this
            ->where($condition1)
            ->count();
        $result['total'] = ceil( $count/$limit );
        return $result;
    }
	
    public function turnover() 
    {
            $field = "FROM_UNIXTIME(ctime, '%Y-%m-%d') as days, SUM(price) as total_money";
            $condition = [
                    //'ctime' => ['between', $dateTime],
                    'pay_status' => 1
            ];
            $list = $this->where($condition)->field($field)->group('days')->select();
            $new_list = [];
            foreach($list as $info) {
                    $new_list[$info['days']] = $info->total_money;
            }
            return $new_list;
            /*list($start_time, $end_time) = $dateTime;
            $date = ceil(($end_time-$start_time)/86400);
            for($i = 0; $i>$date; $i++) {
                    $day = date('Y-m-d', $start_time+$i*86400);
                    if(!isset($new_list[$day])) {
                            $new_list[$day] = 0;
                    } 
            }*/

    }
}